#!/bin/bash
# 脚本测试，主机环境：Ubuntu-20.04

# 设置使用的百分比
MEM_USED_PCT=80
DISK_USE_PCT=80
CPU_USED_PCT=80

MEM=`free -m | awk 'NR==2{printf "%d", $3*100/$2 }'`
DISK=`df -h | awk '$NF=="/"{printf "%d", $5}'`
CPU=`top -b -n 1 | grep Cpu | awk '{printf "%d", $4}' | cut -f 1 -d "."`

#echo "MEM USE: $MEM%"
#echo "DISK USE: $DISK%"
#echo "CPU USE: $CPU%"

# 使用的百分比大于等于设定值，显示 *** unhealt, 否则显示使用百分比.并输出到日记文件
if [ $MEM -ge $MEM_USED_PCT ] ; then
         echo "MEM unhealth" - $(date +%Y-%m-%d[%H:%M:%S]) >> /var/log/MEM-`date +%Y%m%d`.log 
    else
         echo "MEM USE: $MEM%" - $(date +%Y-%m-%d[%H:%M:%S]) >> /var/log/MEM-`date +%Y%m%d`.log 

fi

if [ $DISK -ge $DISK_USE_PCT ] ; then
         echo "DISK unhealth" - $(date +%Y-%m-%d[%H:%M:%S]) >> /var/log/DISK-`date +%Y%m%d`.log 
    else
         echo "DISK USE: $DISK%" - $(date +%Y-%m-%d[%H:%M:%S]) >> /var/log/DISK-`date +%Y%m%d`.log 
fi

if [ $CPU -ge $CPU_USED_PCT ] ; then
         echo "CPU unhealth" - $(date +%Y-%m-%d[%H:%M:%S]) >> /var/log/CPU-`date +%Y%m%d`.log 
    else
         echo "MEM CPU: $CPU%" - $(date +%Y-%m-%d[%H:%M:%S]) >> /var/log/CPU-`date +%Y%m%d`.log 
fi


# 使用ansible+shell脚本进行环境巡检 <https://blog.csdn.net/weixin_39836585/article/details/103576116>
# root@ubuntu:~# ./check.sh 
# MEM USE: 38%
# DISK USE: 48%
# CPU USE: 8%